<template>
  <view>{{ err }}</view>
</template>

<script setup>
import { ref } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { http } from "@/uni_modules/uview-plus";
import {
  SET_OPENID,
  GET_OPENID,
  GET_TELD_TOKEN_EXPIRE_TIME,
  SET_TELD_TOKEN_EXPIRE_TIME,
  SET_SESSION_KEY,
} from "./../../utils/token";
import useUserStore from "./../../store/user";
const err = ref("");
const wxLogin = () => {
  // return true;
  console.log("获取信息");
  // 如果已存在 OPENID 不需要重新登录
  if (GET_OPENID()) {
    return true;
  }
  return new Promise((resolve, reject) => {
    uni.getUserInfo({
      desc: "登录数据",
      success: (res) => {
        resolve(true);
      },
      fail: (error) => {
        err.value = error;
        reject(error);
      },
    });
  }).then((res) => {
    return wxLogin2(res);
  });
};
const wxLogin2 = (signal) => {
  console.log("wxlogin-2:");
  const store = useUserStore();
  if (signal) {
    return new Promise((resolve, reject) => {
      uni.login({
        success(lres) {
          console.log(lres);
          if (lres.errMsg === "login:ok") {
            // console.log("uni.$u.http:", uni.$u.http);
            http.get(`/pay/openId?jsCode=${lres.code}`).then((ores) => {
              console.log("ores:", ores);
              // userStore.openid = ores.openid;
              SET_OPENID(ores.openid);
              SET_SESSION_KEY(ores.session_key);
              store.updateOpenId(ores.openid);
              resolve(true);
            });
          }
        },
        fail: (error) => {
          err.value = error;
          reject(error);
        },
      });
    });
  }
};

const fetchTeldToken = async (store) => {
  console.log("123:", 123);

  // return true;
  // 这里示例使用 Promise 包裹 wx.request 来实现异步请求
  return new Promise((resolve, reject) => {
    uni.request({
      url: "https://backend-system-cluster01.ems.tckdq.com/teld/explain/query_token",
      data: {
        OperatorID: "MACFP6275",
        OperatorSecret: "abJCZunnRfZtk506",
      },
      header: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "X-Requested-With": "XMLHttpRequest",
      },
      method: "POST",
      sslVerify: true,
      success: ({ data, statusCode, header }) => {
        if (data.code === 200) {
          store.updateTeldToken(data.data.AccessToken);
          SET_TELD_TOKEN_EXPIRE_TIME();
          resolve(true);
        }
      },
      fail: (error) => {
        err.value = error;
        reject(error);
      },
    });
  });
};
onShow(async () => {
  console.log("App Show");
  const store = useUserStore();
  const now = new Date().getTime();
  const EXPIRE_TIME = GET_TELD_TOKEN_EXPIRE_TIME();
  const OPENID = GET_OPENID();

  try {
    // 已有 teld token 且未超过过期时间 且 openid 不为空
    if (store.teldToken && EXPIRE_TIME && now < EXPIRE_TIME && OPENID) {
      uni.switchTab({ url: "/pages/index/index" });
      return;
    }
    const a = await fetchTeldToken(store);
    const b = await wxLogin();
    console.log("a,b:", a, b);

    if (a && b) {
      uni.switchTab({ url: "/pages/index/index" });
    }
  } catch (error) {
    err.value = error;
  }

  //   uni.request({
  //     url: "https://backend-system-cluster01.ems.tckdq.com/teld/explain/query_token",
  //     data: {
  //       OperatorID: "MACFP6275",
  //       OperatorSecret: "abJCZunnRfZtk506",
  //     },
  //     header: {
  //       Accept: "application/json",
  //       "Content-Type": "application/json",
  //       "X-Requested-With": "XMLHttpRequest",
  //     },
  //     method: "POST",
  //     sslVerify: true,
  //     success: ({ data, statusCode, header }) => {
  //       if (data.code === 200) {
  //         store.updateTeldToken(data.data.AccessToken);
  //         SET_TELD_TOKEN_EXPIRE_TIME();
  //       }
  //     },
  //     fail: (error) => {},
  //   });
});
</script>

<style lang="scss" scoped></style>
